package com.example.android.navigationdrawerexample;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.agm.android.constants.Constants;
import com.agm.android.sqllite.dao.UtenteDataSource;
import com.agm.android.task.SyncTask;
import com.agm.dto.Utente;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Activity Che visualizza la pagina di login o effettua direttamente la login se l'utente vuole rimanere loggato
 */
public class LoginActivity extends Activity {

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;


	private String mUsername;
	private String mPassword;
	private Intent intent;

	private EditText mEmailView;
	private EditText mPasswordView;
	private CheckBox rimaniConnesso;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	private UtenteDataSource dao = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		intent = new Intent(this, MainActivity.class);
		rimaniConnesso =  (CheckBox) findViewById(R.id.checkRimaniConnesso);
		dao = new UtenteDataSource(this); 
		dao.open();
		List<Utente> listaUtenti = dao.getAllUenti();
		if(listaUtenti != null && listaUtenti.size()>0 && App.utente == null){
			Utente utenteTmp = dao.getAllUenti().get(0);
			mUsername = utenteTmp.getUserid();
			mPassword = utenteTmp.getPassword() ;
			attemptLogin();
		}
		
		if (App.utente != null) {
			startActivity(intent);
			finish();
		} else if(mUsername == null || "".equals(mUsername)){
			setContentView(R.layout.activity_login);

			// Set up the login form.
			mUsername = getIntent().getStringExtra(EXTRA_EMAIL);
			mEmailView = (EditText) findViewById(R.id.email);
			mEmailView.setText(mUsername);

			mPasswordView = (EditText) findViewById(R.id.password);
			mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
						@Override
						public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
							if (id == R.id.login || id == EditorInfo.IME_NULL) {
								attemptLogin();
								return true;
							}
							return false;
						}
					});

			mLoginFormView = findViewById(R.id.login_form);
			mLoginStatusView = findViewById(R.id.login_status);
			mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

			findViewById(R.id.sign_in_button).setOnClickListener(
					new View.OnClickListener() {
						@Override
						public void onClick(View view) {
							rimaniConnesso =  (CheckBox) findViewById(R.id.checkRimaniConnesso);
							attemptLogin();
						}
					});
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}
		boolean cancel = false;
		View focusView = null;
		// Reset errors.
		if(mEmailView != null){
			mEmailView.setError(null);
		}
		if(mPasswordView != null){
			mPasswordView.setError(null);
		}
		if(mUsername == null || "".equals(mUsername)){
			// Store values at the time of the login attempt.
			mUsername = mEmailView.getText().toString();
			mPassword = mPasswordView.getText().toString();
//			mEmail = "alberto645";
//			mPassword = "otrebla1983";
			// Check for a valid password.
			if (TextUtils.isEmpty(mPassword)) {
				mPasswordView.setError(getString(R.string.error_field_required));
				focusView = mPasswordView;
				cancel = true;
			}

			// Check for a valid email address.
			if (TextUtils.isEmpty(mUsername)) {
				mEmailView.setError(getString(R.string.error_field_required));
				focusView = mEmailView;
				cancel = true;
			}
			if (cancel) {
				focusView.requestFocus();
			}else{
				mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
				showProgress(true);
			}
		}

		if (!cancel) {

			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);

		}

	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if(mLoginStatusView != null){
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
				int shortAnimTime = getResources().getInteger(
						android.R.integer.config_shortAnimTime);
				
					mLoginStatusView.setVisibility(View.VISIBLE);
					mLoginStatusView.animate().setDuration(shortAnimTime)
							.alpha(show ? 1 : 0)
							.setListener(new AnimatorListenerAdapter() {
								@Override
								public void onAnimationEnd(Animator animation) {
									mLoginStatusView.setVisibility(show ? View.VISIBLE
											: View.GONE);
								}
							});
		
					mLoginFormView.setVisibility(View.VISIBLE);
					mLoginFormView.animate().setDuration(shortAnimTime)
							.alpha(show ? 0 : 1)
							.setListener(new AnimatorListenerAdapter() {
								@Override
								public void onAnimationEnd(Animator animation) {
									mLoginFormView.setVisibility(show ? View.GONE
											: View.VISIBLE);
								}
							});
				} else {
					// The ViewPropertyAnimator APIs are not available, so simply show
					// and hide the relevant UI components.
					mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
					mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
				}
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.
			JSONObject holder = new JSONObject();
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httpost = new HttpPost(Constants.URL_REST + "getUtente");
			ObjectMapper mapper = new ObjectMapper();
			try {
				setUtente(holder, httpclient, httpost, mapper);
				if ("".equals(App.utente.getUserid())) {
					return false;
				}
				SyncTask.setLega(mapper);
				SyncTask.setRosa(mapper);
				SyncTask.setCalendario(mapper);
				SyncTask.setClassifica(mapper);
				startActivity(intent);
				finish();
			} catch (JSONException e) {
				e.printStackTrace();
				return false;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return false;
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			
			return true;
		}


		private void setUtente(JSONObject holder, DefaultHttpClient httpclient,
				HttpPost httpost, ObjectMapper mapper) throws JSONException,
				UnsupportedEncodingException, IOException,
				ClientProtocolException, JsonParseException,
				JsonMappingException {
			holder.put(new String("username"), mUsername);
			holder.put(new String("password"), mPassword);
			StringEntity se = new StringEntity(holder.toString());

			httpost.setEntity(se);

			httpost.setHeader("Accept", "application/json");
			httpost.setHeader("Content-type", "application/json");
			HttpResponse response = httpclient.execute(httpost);
			HttpEntity httpEntity = response.getEntity();
			InputStream is = httpEntity.getContent();
			Utente[] utenti = mapper.readValue(is, Utente[].class);
			App.utente = utenti[0];
			App.utente.setPassword(mPassword);
			if(rimaniConnesso != null && rimaniConnesso.isChecked()){
				dao.open();
				dao.deleteAll();
				dao.createUtente(App.utente.getUserid(), App.utente.getPassword());
			}
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			showProgress(false);

			if (success) {
				finish();
			} else {
				mPasswordView
						.setError(getString(R.string.error_incorrect_password));
				mPasswordView.requestFocus();
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(false);
		}
	}
}
